package cn.com.websocket.config;

import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.concurrent.TimeUnit;

/**
 * redicache 工具类
 */
@Slf4j
@Component
public class RedisUtil {

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    /**
     * 自增
     * @param key
     * @return
     */
    public long increment(String key) {
        return increment(key,2*60L);
    }

    /**
     * <p>设置redis的原子自增(每次调用并不会覆盖过期的时间)</p>
     * @param key
     * @param timeout 失效时间(秒为单位)
     * */
    public long increment(String key,Long timeout){
        return increment(key,timeout,TimeUnit.SECONDS);
    }

    /**
     * <p>设置redis的原子自增(每次调用并不会覆盖过期的时间)</p>
     * @param key
     * @param timeout 失效时间(秒为单位)
     * */
    public long increment(String key,Long timeout,TimeUnit timeUnit){
        long count = stringRedisTemplate.opsForValue().increment(key, 1);
        if (count == 1) {
            stringRedisTemplate.expire(key, timeout, timeUnit);
        }
        return count;
    }

    /**
     * 判断缓存中是否有对应的value
     * @param key
     * @return
     */
    public boolean exists(final String key) {
        return stringRedisTemplate.hasKey(key);
    }

    /**
     * 写入缓存
     *
     * @param key 键
     * @param value 值
     * @param expireTime 失效时间(默认秒为单位)
     * @return
     */
    public boolean set(final String key, Object value, Long expireTime) {
        return set(key,value,TimeUnit.SECONDS,expireTime);
    }

    /**
     * 写入缓存
     *
     * @param key 键
     * @param value 值
     * @param timeUnit 时间单位
     * @param expireTime 失效时间
     * @return
     */
    public boolean set(final String key, Object value,TimeUnit timeUnit, Long expireTime) {
        boolean result = false;
        try {
            ValueOperations<String, String> operations = stringRedisTemplate.opsForValue();
            operations.set(key, value.toString());
            stringRedisTemplate.expire(key, expireTime, timeUnit);
            result = true;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }
}